package com.comment.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.comment.pojo.Comment;
import com.comment.util.DBUtil;

public class CommentAction {
	
	public List<Comment> query() {
		Connection conn = DBUtil.getConnection();
		String sql = "select * from comment";
		List<Comment> list = new ArrayList<Comment>();
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			ResultSet rs = pstm.executeQuery();
			while(rs.next()){
				Comment comment = new Comment();
				comment.setId(rs.getInt("id"));
				comment.setUsername(rs.getString("username"));
				comment.setContact(rs.getString("contact"));
				comment.setTopic(rs.getString("topic"));
				comment.setContent(rs.getString("content"));
				list.add(comment);
			}
			rs.close();
			pstm.close();
				
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public void add(String username, String contact, String topic, String content) {
		Connection conn = DBUtil.getConnection();
		String sql = "insert into comment (username,contact,topic,content) values(?,?,?,?)";
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			pstm.setString(1, username);
			pstm.setString(2, contact);
			pstm.setString(3, topic);
			pstm.setString(4, content);
			pstm.executeUpdate();
			pstm.close();
				
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
